<template>
  <div class="favorite-list">
    <div class="header">
      <h2>我的收藏</h2>
      <div class="stats">
        <el-tag type="success" effect="dark">共 {{ pagination.total }} 篇收藏</el-tag>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <template #header>
        <div class="search-header">
          <span>搜索条件</span>
        </div>
      </template>
      <el-form :model="searchForm" label-width="80px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="8" :xs="24" :sm="12" :md="8">
            <el-form-item label="标题">
              <el-input 
                v-model="searchForm.title" 
                placeholder="请输入文献标题" 
                clearable 
                prefix-icon="Search"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24" :sm="12" :md="8">
            <el-form-item label="作者">
              <el-input 
                v-model="searchForm.authors" 
                placeholder="请输入作者" 
                clearable 
                prefix-icon="User"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24" :sm="12" :md="8">
            <el-form-item label="收藏时间">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="searchFavorites" round>
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch" round>
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <div class="toolbar">
        <div class="left-actions">
          <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
          <el-button 
            type="danger" 
            :disabled="selectedIds.length === 0"
            @click="batchRemoveFavorites"
            round
          >
            <el-icon><Delete /></el-icon>
            批量取消收藏
          </el-button>
        </div>
        <div class="right-actions">
          <el-button @click="exportFavorites" :disabled="favoriteList.length === 0" round>
            <el-icon><Download /></el-icon>
            导出收藏列表
          </el-button>
          <el-button @click="refreshList" :loading="loading" round>
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 收藏列表 -->
    <el-card class="favorite-content">
      <el-table 
        v-loading="loading" 
        :data="favoriteList" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
        highlight-current-row
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="title" label="标题" min-width="250">
          <template #default="{ row }">
            <div class="title-cell">
              <el-link 
                type="primary" 
                @click="$router.push(`/literature/detail/${row.id}`)"
                :underline="false"
              >
                {{ row.title }}
              </el-link>
              <div class="title-meta">
                <el-tag size="small" type="warning" v-if="isRecent(row.createTime)">最近收藏</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="authors" label="作者" width="150" />
        
        <el-table-column prop="keywords" label="关键词" width="200">
          <template #default="{ row }">
            <div class="keyword-cell">
              <el-tag 
                v-for="keyword in row.keywords?.split(',').slice(0, 3)" 
                :key="keyword" 
                size="small" 
                type="success"
                style="margin-right: 5px; margin-bottom: 5px;"
              >
                {{ keyword }}
              </el-tag>
              <span v-if="row.keywords?.split(',').length > 3" class="more-keywords">
                +{{ row.keywords.split(',').length - 3 }}
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="收藏时间" width="180">
          <template #default="{ row }">
            <div class="time-cell">
              <div>{{ formatDate(row.createTime) }}</div>
              <div class="time-ago">{{ getTimeAgo(row.createTime) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="journal" label="期刊" width="150" />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="$router.push(`/literature/detail/${row.id}`)"
              round
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="removeFavorite(row)"
              round
            >
              取消收藏
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        style="margin-top: 20px; justify-content: center;"
      />
    </el-card>

    <!-- 笔记对话框 -->
    <el-dialog v-model="noteDialogVisible" title="添加笔记" width="500px" center>
      <el-form :model="noteForm" label-width="80px">
        <el-form-item label="笔记内容">
          <el-input 
            v-model="noteForm.content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入您的笔记..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="noteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNote">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Delete } from '@element-plus/icons-vue'
import { literatureApi } from '@/api/literature'
import type { PageResult, Literature } from '@/api/literature'

// 响应式数据
const loading = ref(false)
const favoriteList = ref<Literature[]>([])
const selectedIds = ref<number[]>([])
const selectAll = ref(false)
const noteDialogVisible = ref(false)

const searchForm = reactive({
  title: '',
  authors: '',
  dateRange: [] as string[]
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const noteForm = reactive({
  favoriteId: 0 as number | null,
  content: ''
})

// 方法
const searchFavorites = () => {
  pagination.current = 1
  loadFavoriteList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    authors: '',
    dateRange: [] as string[]
  })
  searchFavorites()
}

const refreshList = () => {
  loadFavoriteList()
}

const loadFavoriteList = async () => {
  loading.value = true
  try {
    // 构造后端能识别的查询参数，不包含dateRange字段
    const query = {
      title: searchForm.title,
      authors: searchForm.authors,
      current: pagination.current,
      size: pagination.size
    }
    
    const response: PageResult<Literature> = await literatureApi.getFavorites(query)
    
    favoriteList.value = response.records
    pagination.total = response.total
    loading.value = false
  } catch (error) {
    ElMessage.error('加载收藏列表失败')
    loading.value = false
  }
}

const handleSelectionChange = (selection: Literature[]) => {
  selectedIds.value = selection.map(item => item.id)
  selectAll.value = selection.length === favoriteList.value.length && selection.length > 0
}

const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedIds.value = favoriteList.value.map(item => item.id)
  } else {
    selectedIds.value = []
  }
}

const removeFavorite = async (row: Literature) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏这篇文献吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
      })
    
    await literatureApi.toggleFavorite(row.id)
    ElMessage.success('取消收藏成功')
    loadFavoriteList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const batchRemoveFavorites = async () => {
  try {
    await ElMessageBox.confirm(`确定要取消收藏选中的 ${selectedIds.value.length} 篇文献吗？`, '批量操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 批量取消收藏
    for (const id of selectedIds.value) {
      await literatureApi.toggleFavorite(id)
    }
    
    ElMessage.success('批量取消收藏成功')
    selectedIds.value = []
    selectAll.value = false
    loadFavoriteList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const exportFavorites = () => {
  ElMessage.info('导出功能开发中...')
}

const saveNote = async () => {
  if (!noteForm.content.trim()) {
    ElMessage.warning('请输入笔记内容')
    return
  }
  
  try {
    ElMessage.success('笔记保存成功')
    noteDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  loadFavoriteList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadFavoriteList()
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const getTimeAgo = (dateStr: string) => {
  if (!dateStr) return '-'
  const now = new Date()
  const date = new Date(dateStr)
  const diff = now.getTime() - date.getTime()
  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  if (days > 0) return `${days}天前`
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  if (hours > 0) return `${hours}小时前`
  
  const minutes = Math.floor(diff / (1000 * 60))
  if (minutes > 0) return `${minutes}分钟前`
  
  return '刚刚'
}

const isRecent = (dateStr: string) => {
  if (!dateStr) return false
  const now = new Date()
  const date = new Date(dateStr)
  const diff = now.getTime() - date.getTime()
  // 7天内为最近
  return diff < 7 * 24 * 60 * 60 * 1000
}

// 生命周期
onMounted(() => {
  loadFavoriteList()
})
</script>

<style scoped>
.favorite-list {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.stats {
  display: flex;
  gap: 10px;
}

.search-card, .toolbar-card, .favorite-content {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.search-header, .toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar {
  padding: 15px 20px;
}

.left-actions, .right-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.title-cell {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.title-meta {
  display: flex;
  gap: 5px;
}

.keyword-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 3px;
}

.more-keywords {
  font-size: 12px;
  color: #999;
}

.time-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-ago {
  font-size: 12px;
  color: #999;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
}

@media (max-width: 768px) {
  .favorite-list {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .el-col {
    margin-bottom: 15px;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .left-actions, .right-actions {
    justify-content: center;
  }
}
</style>